import {ClipboardUtils, MYel} from "../../utils/clipboardUtils";
import {ElMessage} from "element-plus";
import {Directive} from "vue";

export const ClickCopy: Directive = {
  mounted(el: MYel, binding) {
    el.__copyText__ = (e: MouseEvent) => {
      if (ClipboardUtils.isSupported()) {
        ClipboardUtils.copyText(el, binding.value, e).then(() => {
          ElMessage.success('已复制到剪切板')
        }).catch(() => {
          ElMessage.error('复制失败')
        })
      } else {
        ElMessage.error('当前浏览器不支持复制功能')
      }
    }
    el.addEventListener('click', el.__copyText__)
  },
  updated(el: MYel, binding) {
    ClickCopy.unmounted(el, binding)
    ClickCopy.mounted(el, binding)
  },
  unmounted(el: MYel, binding) {
    el.removeEventListener('click', el.__copyText__)
  }
}
